import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { createPostSchema } from '@/lib/validations';
import { verifyToken } from '@/lib/auth';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const status = searchParams.get('status');
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '10');
    const skip = (page - 1) * limit;

    const where = status ? { status: status as any } : { status: 'published' };
    
    const [posts, total] = await Promise.all([
      prisma.post.findMany({
        where,
        include: {
          author: {
            select: { id: true, name: true, email: true }
          },
          tags: {
            include: {
              tag: true
            }
          }
        },
        orderBy: { createdAt: 'desc' },
        skip,
        take: limit,
      }),
      prisma.post.count({ where })
    ]);

    return NextResponse.json({
      posts: posts.map(post => ({
        ...post,
        author: post.author.name,
        tags: post.tags.map(pt => pt.tag.name)
      })),
      pagination: {
        page,
        limit,
        total,
        pages: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    console.error('获取文章列表失败:', error);
    return NextResponse.json(
      { error: '获取文章列表失败' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const authHeader = request.headers.get('authorization');
    if (!authHeader?.startsWith('Bearer ')) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      );
    }

    const token = authHeader.substring(7);
    const payload = await verifyToken(token);
    if (!payload) {
      return NextResponse.json(
        { error: '无效的访问令牌' },
        { status: 401 }
      );
    }

    const body = await request.json();
    
    // 获取当前用户信息
    const user = await prisma.user.findUnique({
      where: { id: payload.userId }
    });
    
    if (!user) {
      return NextResponse.json(
        { error: '用户不存在' },
        { status: 404 }
      );
    }

    // 构建文章数据，使用当前用户作为作者
    const postData = {
      ...body,
      authorId: user.id,
      status: body.status || 'DRAFT'
    };
    
    const validatedData = createPostSchema.parse(postData);

    // 检查 slug 是否已存在
    const existingPost = await prisma.post.findUnique({
      where: { slug: validatedData.slug }
    });

    if (existingPost) {
      return NextResponse.json(
        { error: 'URL别名已存在' },
        { status: 400 }
      );
    }

    // 创建或获取标签
    const tagIds = await Promise.all(
      validatedData.tags.map(async (tagName) => {
        const tag = await prisma.tag.upsert({
          where: { name: tagName },
          update: {},
          create: { name: tagName }
        });
        return tag.id;
      })
    );

    // 创建文章
    const post = await prisma.post.create({
      data: {
        ...validatedData,
        publishedAt: validatedData.status === 'PUBLISHED' ? new Date() : null,
        tags: {
          create: tagIds.map(tagId => ({
            tagId
          }))
        }
      },
      include: {
        author: {
          select: { id: true, name: true, email: true }
        },
        tags: {
          include: {
            tag: true
          }
        }
      }
    });

    return NextResponse.json({
      ...post,
      tags: post.tags.map(pt => pt.tag.name)
    }, { status: 201 });
  } catch (error) {
    console.error('创建文章失败:', error);
    if (error instanceof Error && error.name === 'ZodError') {
      return NextResponse.json(
        { error: '数据验证失败', details: error.message },
        { status: 400 }
      );
    }
    return NextResponse.json(
      { error: '创建文章失败' },
      { status: 500 }
    );
  }
}
